package com.ghsc.ghxc.jsb.ui.home.activity

import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import android.webkit.JavascriptInterface
import android.webkit.ValueCallback
import android.webkit.WebResourceRequest
import android.webkit.WebView
import android.widget.LinearLayout
import com.cn.appcore.base.BaseVMActivity
import com.cn.appcore.event.RxBus
import com.cn.appcore.event.RxBusBean
import com.cn.appcore.ext.asColor
import com.cn.appcore.ext.loge
import com.cn.appcore.ext.showToast
import com.cn.appcore.ext.startKtxActivityKill
import com.cn.appcore.utils.RxHelper
import com.ghsc.ghxc.jsb.R
import com.ghsc.ghxc.jsb.config.CustKey
import com.ghsc.ghxc.jsb.databinding.ActivityWebviewBinding
import com.ghsc.ghxc.jsb.ui.main.MainActivity
import com.just.agentweb.AgentWeb
import com.just.agentweb.AgentWebConfig
import com.just.agentweb.AgentWebSettingsImpl
import com.just.agentweb.DefaultWebClient
import com.just.agentweb.WebChromeClient
import com.just.agentweb.WebViewClient
import io.reactivex.Observable

/**
 * 项目：GuoHuaJsb
 * 包名：com.ghsc.ghxc.jsb.ui.home.activity
 * 类名：WebViewActivity
 * 创建时间：2024/4/24 15:04
 * 创建人 @author： xiaolin
 * 描述 ：Todo...
 */
class WebViewActivity : BaseVMActivity<WebViewViewModel, ActivityWebviewBinding>(){
    override fun attachLayoutRes(): Int {
        return R.layout.activity_webview
    }

    override fun attachVMClass(): Class<WebViewViewModel>? {
       return WebViewViewModel::class.java
    }


    var bundle: Bundle?=null
    var url: String=""
    var showBar:Boolean=true
    var title:String =""
    var agentWeb: AgentWeb?= null

    override fun initImmersionBar() {
        super.initImmersionBar()
        mImmersionBar!!.statusBarDarkFont(true).init()
    }
    override fun initView() {
        bundle=intent.extras
        url=bundle!!.getString("url","")
        showBar=bundle!!.getBoolean("showBar",true)
        title=bundle!!.getString("title","")
        if (!showBar)
            binding.bar.llContainer.visibility= View.GONE
        else binding.bar.llContainer.visibility= View.VISIBLE
        loge("url="+url)
        agentWeb= AgentWeb.with(this)
            .setAgentWebParent(binding.llContainer, LinearLayout.LayoutParams(-1, -1))
            .useDefaultIndicator(R.color.btn_default_color.asColor(), 2)
            .setWebChromeClient(webChromeClient)
            .setWebViewClient(webViewClient)
            .setAgentWebWebSettings(AgentWebSettingsImpl.getInstance())
            .setMainFrameErrorView(
                R.layout.layout_agentweb_error_page,
                -1
            ) //参数1是错误显示的布局，参数2点击刷新控件ID -1表示点击整个布局都刷新
            .setSecurityType(AgentWeb.SecurityType.STRICT_CHECK)
//            .setWebLayout(WebLayout(this))
            .setOpenOtherPageWays(DefaultWebClient.OpenOtherPageWays.ASK) //打开其他应用时，弹窗咨询用户是否前往其他应用
            .interceptUnkownUrl() //拦截找不到相关页面的Url
            .createAgentWeb()
            .ready()
            .go(url)
        binding.run {
            bar.topTitle.text = ""
            bar.topLeftView.setOnClickListener {
                if (!agentWeb!!.back()) {
                    finish()
                }
            }
        }
        //设置webView滑动模式
        agentWeb!!.webCreator.webView.overScrollMode = WebView.OVER_SCROLL_NEVER
        //js交互  暂时没用到。
        agentWeb!!.jsInterfaceHolder.addJavaObject("android", AndroidInterface())
        //调用H5页面的方法示例,quickCallJs方法传参是js定义的方法名字
        //https://github.com/Justson/AgentWeb/blob/androidx/sample/src/main/java/com/just/agentweb/sample/fragment/JsAgentWebFragment.java
        ////agentWeb.jsAccessEntrace.quickCallJs("")
    }
    private var FILE_CHOOSER_REQUEST_CODE = 1
    private var filePathCallbacks: ValueCallback<Array<Uri>>? = null

    private val webChromeClient: WebChromeClient = object : WebChromeClient() {
        override fun onReceivedTitle(view: WebView, title: String) {
            super.onReceivedTitle(view, title)
            if (showBar && TextUtils.isEmpty(title))
                binding.bar.topTitle.text = title
        }

        override fun onShowFileChooser(
            webView: WebView?,
            filePathCallback: ValueCallback<Array<Uri>>?,
            fileChooserParams: FileChooserParams?
        ): Boolean {
            // 处理文件选择器的逻辑
            // 你可以通过启动一个文件选择器的 Intent，让用户选择本地文件
            // 然后在选择完成后，调用 filePathCallback.onReceiveValue(selectedUris);
            // 保存 filePathCallback，以便在选择完成后使用
            filePathCallbacks = filePathCallback
            // 启动文件选择器的 Intent
            val intent = Intent(Intent.ACTION_GET_CONTENT)
            intent.addCategory(Intent.CATEGORY_OPENABLE)
            intent.type = "*/*"
            // 启动文件选择器的 Activity
            startActivityForResult(intent, FILE_CHOOSER_REQUEST_CODE)
            return true

        }
    }
    private val webViewClient: WebViewClient = object : WebViewClient() {
        override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest): Boolean {
            return super.shouldOverrideUrlLoading(view, request)
        }

        override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
            super.onPageStarted(view, url, favicon)
        }
    }
//    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
//        return if (agentWeb!!.handleKeyEvent(keyCode, event)) {
//            true
//        } else super.onKeyDown(keyCode, event)
//    }

    override fun onPause() {
        agentWeb!!.webLifeCycle.onPause()
        super.onPause()
    }

    override fun onResume() {
        agentWeb!!.webLifeCycle.onResume()
        super.onResume()
    }
    override fun onDestroy() {
        super.onDestroy()
        RxBus.getDefault().post(RxBusBean(CustKey.CHECK_PAY_RESULT, CustKey.CHECK_PAY_RESULT))
        //清空缓存
        AgentWebConfig.clearDiskCache(this)
        agentWeb!!.webLifeCycle.onDestroy()
    }

    //这里是和webveiw做交互的
    inner class AndroidInterface {
        @JavascriptInterface
        fun closePage() {
            runOnUiThread {
                finish()
            }
        }
        @JavascriptInterface
        fun goHome() {
            runOnUiThread {
                startKtxActivityKill<MainActivity>()
            }
        }
        //        @JavascriptInterface
//        fun scanCode() {
//            //扫一扫
//            PermissionX.init(this@WebViewActivity)
//                .permissions(
//                    Manifest.permission.CAMERA)
//                .request { allGranted, _, _ ->
//                    if (allGranted) {
//                        val intent = Intent(this@WebViewActivity, ScanActivity::class.java)
//                        startActivityForResult(intent, onActivityResult_To_CODE)
//                    } else {
//                        showMsg("需开启权限才能进行扫码操作")
//                    }
//                }
//        }
        @JavascriptInterface
        fun saveScanCode(base64Str :String) {
            loge("图="+base64Str)
//            var bitmap= ImgUtils.base64ToBitmap2(base64Str)
//            Observable.create<String> { e ->
//                var shareImgUrl = saveBitmap(this@WebViewActivity,bitmap!!,"ccc")
//                shareImgUrl?.let {
//                    e.onNext(it)
//                    e.onComplete()
//                }
//            }.compose(RxHelper.rxSchedulerHelper()).subscribe {
//                it?.let {
//                    loge("图片已保存至相册")
//                    showToast("图片已保存至相册")
//                }
//            }
        }


    }
    companion object {
        const  val onActivityResult_To_CODE = 11010
    }
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        when (resultCode) {
            RESULT_OK -> if (requestCode == FILE_CHOOSER_REQUEST_CODE) {
                // 获取选择的文件 Uri
                val selectedUri: Uri? = data!!.data
                // 将选择的文件 Uri 转为 Uri 数组，并传递给 WebView
                val selectedUris = arrayOf(selectedUri!!)
                filePathCallbacks?.onReceiveValue(selectedUris)
                // 重置 filePathCallback，确保下次调用时不会使用已经处理过的回调
                filePathCallbacks = null
            }
            onActivityResult_To_CODE ->                 //上门返回来的地址。
                if (data != null) {
                    var resultData = data.getStringExtra("resultData")
                    loge("扫描的结果："+resultData)
                    agentWeb!!.urlLoader.loadUrl("javascript:scanCodeCallback($resultData)")
                }

        }
    }
}